package com.wyp.didishige.adapter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.wyp.didishige.activity.ImageBrowserActivity;
import com.wyp.didishige.activity.UserInfoActivity;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.config.Constants;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.ToastUtil;
import com.wyp.didishige.R;
import com.wyp.didishige.activity.DynamicDetailActivity;
import com.wyp.didishige.model.Dynamic;
import com.wyp.didishige.model.User;
import com.wyp.didishige.utils.DateUtil;
import com.wyp.didishige.utils.ImageLoadOptions;
import com.wyp.didishige.utils.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.bmob.im.BmobUserManager;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.DeleteListener;

/**
 * 附近的人适配器
 * Created by horry on 2015/4/14.
 */
public class DiscoverAdapter extends BaseListAdapter<Dynamic> {
    User loginUser = null;
    public DiscoverAdapter(Context context, List<Dynamic> list) {
        super(context, list);

        this.mContext = context;
        this.list = list;
        mInflater = LayoutInflater.from(context);
        loginUser = BmobUserManager.getInstance(mContext).getCurrentUser(User.class);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return super.getView(position, convertView, parent);
    }

    @Override
    public View bindView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.near_girl, null);
            holder.comment_count = (TextView) convertView.findViewById(R.id.comment_count);
            holder.read_count = (TextView) convertView.findViewById(R.id.read_count);
            holder.like_count = (TextView) convertView.findViewById(R.id.like_count);
            holder.user_name = (TextView) convertView.findViewById(R.id.user_name);
            holder.publish_community = (TextView) convertView.findViewById(R.id.publish_community);
            holder.distance = (TextView) convertView.findViewById(R.id.distance);
            holder.publish_time = (TextView) convertView.findViewById(R.id.publish_time);
            holder.dynamic_content = (TextView) convertView.findViewById(R.id.dynamic_content);
            holder.user_head = (ImageView) convertView.findViewById(R.id.user_head);
            holder.user_gender = (TextView) convertView.findViewById(R.id.user_gender);
            holder.vip_lv = (ImageView) convertView.findViewById(R.id.vip_lv);
            holder.comment = (LinearLayout) convertView.findViewById(R.id.comment);
            holder.like = (LinearLayout) convertView.findViewById(R.id.like);
            holder.dynamic_address = (TextView) convertView.findViewById(R.id.dynamic_address);
            holder.image1 = (ImageView) convertView.findViewById(R.id.image1);
            holder.image2 = (ImageView) convertView.findViewById(R.id.image2);
            holder.image3 = (ImageView) convertView.findViewById(R.id.image3);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final Dynamic dynamic = list.get(position);

        if (!StringUtils.isNullOrEmpty(dynamic.getAddress())) {
            holder.dynamic_address.setText(dynamic.getAddress());
            holder.dynamic_address.setVisibility(View.VISIBLE);
        } else {
            holder.dynamic_address.setVisibility(View.GONE);
        }

        holder.comment_count.setText(String.format("%d", dynamic.getCommentNum()));
        holder.like_count.setText(String.format("%d", dynamic.getLikeNum()));
        holder.read_count.setText(String.format("%d", dynamic.getReadNum()));
        holder.comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString(Constants.DYNAMIC_ID, dynamic.getObjectId());
                IntentUtil.start_activity((Activity) mContext, DynamicDetailActivity.class, bundle);
            }
        });
        setImages(holder, dynamic);
        if (holder.isLike) {
            holder.like.setEnabled(false);
        } else {
            holder.like.setEnabled(true);
        }
        final User user = dynamic.getAuthor();
        if (user != null) {

            if (user.getAvatar() == null) {
                holder.user_head.setImageResource(R.drawable.ic_launcher);
            } else {
                ImageLoader.getInstance().displayImage(user.getAvatar(), holder.user_head, ImageLoadOptions.getOptions());
            }

            holder.user_name.setText(user.getNick());
            if (!StringUtils.isNullOrEmpty(user.getCommunity())){
                holder.publish_community.setText(user.getCommunity());
                holder.publish_community.setVisibility(View.VISIBLE);
            }else{
                holder.publish_community.setVisibility(View.GONE);
            }

            String age = DateUtil.getAge(user.getUserBirthday()) + "";
            holder.user_gender.setText(age);
            if (user.getSex() != null && user.getSex()) {
                holder.user_gender.setBackgroundResource(R.drawable.user_male_bg);
                holder.user_gender.setCompoundDrawablesWithIntrinsicBounds(mContext.getResources().getDrawable(R.drawable.ic_user_male), null, null, null);
            } else {
                holder.user_gender.setBackgroundResource(R.drawable.user_female_bg);
                holder.user_gender.setCompoundDrawablesWithIntrinsicBounds(mContext.getResources().getDrawable(R.drawable.ic_user_famale), null, null, null);
            }

            int level = dynamic.getAuthor().getLevel();
            if (level >= 1 && level < 3) {
                holder.vip_lv.setImageResource(R.drawable.vip_lv_1);
                holder.vip_lv.setVisibility(View.VISIBLE);
            } else if (level >= 3 && level < 6) {
                holder.vip_lv.setImageResource(R.drawable.vip_lv_3);
                holder.vip_lv.setVisibility(View.VISIBLE);

            } else if (level >= 6 && level < 12) {
                holder.vip_lv.setImageResource(R.drawable.vip_lv_6);
                holder.vip_lv.setVisibility(View.VISIBLE);

            } else if (level >= 9) {
                holder.vip_lv.setImageResource(R.drawable.vip_lv_12);
                holder.vip_lv.setVisibility(View.VISIBLE);

            } else {
                holder.vip_lv.setVisibility(View.GONE);
            }
            holder.user_head.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(Config.KEY_USER_ID, user.getObjectId());
                    bundle.putSerializable("from", "add");
                    IntentUtil.start_activity((Activity) mContext, UserInfoActivity.class, bundle);
                }
            });


        }

        double distance = dynamic.getMeter() / 1000;

        holder.distance.setText(distance + "千米");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        2015-04-22 23:54:13
        Date date = new Date();
        try {
            date = simpleDateFormat.parse(dynamic.getCreatedAt());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);
        holder.publish_time.setText(DateUtil.getDateSpan(calendar.getTimeInMillis() / 1000,
                DateUtil.getTimestamp(new Date())));
        if (StringUtils.isNullOrEmpty(dynamic.getContent())){
            holder.dynamic_content.setVisibility(View.GONE);
        }else{
            holder.dynamic_content.setVisibility(View.VISIBLE);
            holder.dynamic_content.setText(dynamic.getContent());
        }

        return convertView;
    }

    /**
     * 删除
     * @param dynamic
     */
    private void deleteThis(final Dynamic dynamic){
        final AlertDialog.Builder builder=new AlertDialog.Builder(mContext);

        builder.setTitle("删除动态");
        builder.setMessage("确定删除此条动态");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                final ProgressDialog loading=new ProgressDialog(mContext);
                loading.setTitle("提示");
                loading.setMessage("正在删除动态...");
                loading.show();
                dynamic.delete(mContext, new DeleteListener() {
                    @Override
                    public void onSuccess() {
                        list.remove(dynamic);
                        notifyDataSetChanged();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        loading.cancel();
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        ToastUtil.showShort(mContext, "操作失败," + s);
                    }
                });
                dialog.cancel();
            }
        });
        builder.show();
    }
    private void setImages(ViewHolder holder, Dynamic request) {
        if (request.getImages() != null && request.getImages().length != 0) {
            final BmobFile[] imaList = request.getImages();

            int length=imaList.length;

            for (int i = 0; i < length; i++) {
                String url = imaList[i].getUrl();
                switch (i) {
                    case 0:
                        if (!StringUtils.isNullOrEmpty(url)) {
                            ImageLoader.getInstance().displayImage(url, holder.image1, ImageLoadOptions.getOptions());
                        }
                        break;
                    case 1:
                        if (!StringUtils.isNullOrEmpty(url)) {
                            ImageLoader.getInstance().displayImage(url, holder.image2, ImageLoadOptions.getOptions());
                        }
                        break;
                    case 2:
                        if (!StringUtils.isNullOrEmpty(url)) {
                            ImageLoader.getInstance().displayImage(url, holder.image3, ImageLoadOptions.getOptions());
                        }
                        break;
                }

            }
            final ArrayList<BmobFile> bmobFiles = new ArrayList<BmobFile>();
            for (BmobFile file : imaList) {
                bmobFiles.add(file);
            }
            holder.image1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MobclickAgent.onEvent(mContext,"discover_pic_click");
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("photos", bmobFiles);
                    bundle.putInt("position", 0);
                    IntentUtil.start_activity((Activity) mContext, ImageBrowserActivity.class, bundle);
                }
            });
            MobclickAgent.onEvent(mContext, "discover_pic_click");
            holder.image2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("photos", bmobFiles);
                    bundle.putInt("position", 1);
                    IntentUtil.start_activity((Activity) mContext, ImageBrowserActivity.class, bundle);
                }
            });
            holder.image3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MobclickAgent.onEvent(mContext,"discover_pic_click");
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("photos", bmobFiles);
                    bundle.putInt("position", 2);
                    IntentUtil.start_activity((Activity) mContext, ImageBrowserActivity.class, bundle);
                }
            });
            if (length<=0){
                holder.image1.setVisibility(View.GONE);
                holder.image2.setVisibility(View.GONE);
                holder.image3.setVisibility(View.GONE);
            }else if (length==1){
                holder.image1.setVisibility(View.VISIBLE);
                holder.image2.setVisibility(View.GONE);
                holder.image3.setVisibility(View.GONE);
            }else if (length==2){
                holder.image1.setVisibility(View.VISIBLE);
                holder.image2.setVisibility(View.VISIBLE);
                holder.image3.setVisibility(View.GONE);
            }else{
                holder.image1.setVisibility(View.VISIBLE);
                holder.image2.setVisibility(View.VISIBLE);
                holder.image3.setVisibility(View.VISIBLE);
            }
        } else {
            holder.image1.setVisibility(View.GONE);
            holder.image2.setVisibility(View.GONE);
            holder.image3.setVisibility(View.GONE);
        }

    }

    class ViewHolder {
        TextView user_name;
        TextView publish_time;
        TextView dynamic_content;
        TextView distance;
        TextView comment_count;
        TextView read_count;
        TextView like_count;
        TextView publish_community;

        TextView dynamic_address;
        ImageView user_head;
        TextView user_gender;
        ImageView vip_lv;
        LinearLayout comment;
        LinearLayout like;
        boolean isLike = false;//是否赞过


        ImageView image1;
        ImageView image2;
        ImageView image3;
    }
}
